import 'dart:convert';
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:tencent_cloud_chat_demo/db/custom_sticker.dart';

class AuthService {
  // 单例模式
  static final AuthService _instance = AuthService._internal();
  factory AuthService() => _instance;
  AuthService._internal();

  static const String _isLoggedInKey = 'isLoggedIn';
  static const String _authUserSigKey = 'userSig';
  static const String _userIDKey = 'userID';
  static const String _accountKey = 'account';
  static const String _emailKey = 'email';

  static String account = '';

  static const _secureStorage = FlutterSecureStorage();

  // 保存登录状态
  Future<void> saveLoginState({
    required bool isLoggedIn,
    required String userSig,
    required String userID,
    required String account,
    required String email,
  }) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_isLoggedInKey, isLoggedIn); // 确保立即写入
    account = account;
    await Future.wait([
      _secureStorage.write(key: _authUserSigKey, value: userSig),
      _secureStorage.write(key: _userIDKey, value: userID),
      _secureStorage.write(key: _accountKey, value: account),
      _secureStorage.write(key: _emailKey, value: email),
    ]);
  }

  // 检查是否已登录
  static Future<bool> isLoggedIn() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_isLoggedInKey) ?? false;
  }

  // 保存邮箱
  Future<void> saveEmail(String email) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_emailKey, email); // 确保立即写入
    await _secureStorage.write(key: _emailKey, value: email);
  }

  // 保存G10号
  Future<void> saveUserName(String userName) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_accountKey, userName); // 确保立即写入
    account = userName;
    await _secureStorage.write(key: _accountKey, value: userName);
  }

  // 获取保存的token
  static Future<String?> getAuthToken() async {
    return await _secureStorage.read(key: _authUserSigKey);
  }

  // 获取用户ID
  static Future<String?> getUserId() async {
    return await _secureStorage.read(key: _userIDKey);
  }

  // 获取用户账号
  static Future<String?> getAccount() async {
    account = await _secureStorage.read(key: _accountKey) ?? '';
    return account;
  }

  // 获取用户邮箱
  static Future<String?> getEmail() async {
    return await _secureStorage.read(key: _emailKey);
  }

  // 清除登录状态（退出登录）
  static Future<void> clearLoginState() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_isLoggedInKey); // 确保立即写入
    account = '';
    await Future.wait([
      _secureStorage.delete(key: _authUserSigKey),
      _secureStorage.delete(key: _userIDKey),
      _secureStorage.delete(key: _accountKey),
      _secureStorage.delete(key: _emailKey),
    ]);
    // 删除表情包
    clearEmojis();
  }

  // 初始化检查登录状态
  static Future<Map<String, dynamic>> checkInitialLoginState() async {
    final prefs = await SharedPreferences.getInstance();
    final isLoggedIn = prefs.getBool(_isLoggedInKey) ?? false;
    final userSig = await _secureStorage.read(key: _authUserSigKey);
    final userID = await _secureStorage.read(key: _userIDKey);
    final account = await _secureStorage.read(key: _accountKey);
    final email = await _secureStorage.read(key: _emailKey);
    return {
      'isLoggedIn': isLoggedIn,
      'userSig': userSig,
      'userID': userID,
      'account': account,
      'email': email,
    };
  }

  static Future<String?> getDeviceId() async {
    final deviceInfo = DeviceInfoPlugin();

    if (kIsWeb) {
      final webInfo = await deviceInfo.webBrowserInfo;
      return '${webInfo.userAgent ?? 'unknown'}-${webInfo.vendor ?? ''}';
    }

    if (Platform.isAndroid) {
      final androidInfo = await deviceInfo.androidInfo;
      return androidInfo.id;
    }

    if (Platform.isIOS) {
      final iosInfo = await deviceInfo.iosInfo;
      return iosInfo.identifierForVendor ?? 'unknown_ios';
    }

    if (Platform.isWindows) {
      final windowsInfo = await deviceInfo.windowsInfo;
      return '${windowsInfo.deviceId}-${windowsInfo.computerName}';
    }

    if (Platform.isMacOS) {
      final macInfo = await deviceInfo.macOsInfo;
      return macInfo.systemGUID ?? 'unknown_mac';
    }

    if (Platform.isLinux) {
      final linuxInfo = await deviceInfo.linuxInfo;
      return linuxInfo.machineId ?? 'unknown_linux';
    }
    return null;
  }

  static Future<void> addDeviceId(String userId, String newDeviceId) async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'device_ids';

    final jsonStr = prefs.getString(key);
    final Map<String, dynamic> data =
        jsonStr != null ? jsonDecode(jsonStr) : {};

    final List<String> userDevices =
        (data[userId] as List?)?.cast<String>() ?? [];

    if (!userDevices.contains(newDeviceId)) {
      userDevices.add(newDeviceId);

      // 可选：限制最多存储 3 个设备
      if (userDevices.length > 3) {
        userDevices.removeAt(0); // 移除最旧的
      }

      data[userId] = userDevices;
      await prefs.setString(key, jsonEncode(data));
      print("✅ 新设备添加成功");
    } else {
      print("📱 当前设备已存在");
    }
  }

  static Future<bool> isKnownDevice(
      String userId, String currentDeviceId) async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'device_ids';

    final jsonStr = prefs.getString(key);
    final Map<String, dynamic> data =
        jsonStr != null ? jsonDecode(jsonStr) : {};

    final List<String> userDevices =
        (data[userId] as List?)?.cast<String>() ?? [];

    return userDevices.contains(currentDeviceId);
  }

  static Future<bool> checkDeviceForUser(String userId, deviceId) async {
    if (await isKnownDevice(userId, deviceId)) {
      return true;
    } else {
      return false;
      // 这里你可以弹出“新设备登录”的提示或进行身份验证
    }
  }
}
